package com.sd365.permission.centre.service.impl;

import com.github.pagehelper.Page;
import com.sd365.common.core.annotation.mybatis.Pagination;
import com.sd365.common.core.annotation.stuffer.CommonFieldStuffer;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.annotation.stuffer.MethodTypeEnum;
import com.sd365.common.core.common.api.CommonPage;
import com.sd365.common.core.common.constant.EntityConsts;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.code.BizErrorCode;
import com.sd365.common.core.common.pojo.entity.TenantBaseEntity;
import com.sd365.common.core.common.service.AbstractBusinessService;
import com.sd365.common.util.BeanException;
import com.sd365.common.util.BeanUtil;
import com.sd365.permission.centre.dao.mapper.*;
import com.sd365.permission.centre.entity.*;
import com.sd365.permission.centre.pojo.dto.*;
import com.sd365.permission.centre.pojo.query.RoleQuery;
import com.sd365.permission.centre.pojo.query.UserQuery;
import com.sd365.permission.centre.pojo.vo.ResourceVO;
import com.sd365.permission.centre.pojo.vo.RoleCompanyVO;
import com.sd365.permission.centre.pojo.vo.RoleVO;
import com.sd365.permission.centre.service.RoleService;
import com.sd365.permission.centre.service.cache.IRoleCache;
import lombok.extern.slf4j.Slf4j;
import  tk.mybatis.mapper.entity.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;


import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 实现角色服务
 */
@Slf4j
@Service
public class RoleServiceImpl extends AbstractBusinessService implements RoleService {

    @javax.annotation.Resource
    private IRoleCache roleCache;

    @javax.annotation.Resource
    private RoleMapper roleMapper;

    @javax.annotation.Resource
    private ResourceMapper resourceMapper;

    @javax.annotation.Resource
    private RoleResourceMapper roleResourceMapper;

    @javax.annotation.Resource
    private UserRoleMapper userRoleMapper;

    @javax.annotation.Resource
    private UserMapper userMapper;

    @javax.annotation.Resource
    private RoleCompanyMapper roleCompanyMapper;

    @javax.annotation.Resource
    private PositionMapper positionMapper;

    @javax.annotation.Resource
    private CompanyMapper companyMapper;

    @javax.annotation.Resource
    private DepartmentMapper departmentMapper;
    @javax.annotation.Resource
    private OrganizationMapper organizationMapper;
    @javax.annotation.Resource
    private TenantMapper tenantMapper;
    @javax.annotation.Resource
    private IdGenerator idGenerator;

    @Override
    // 把角色和资源关系加载进入redis，已重写
    public Boolean loadRoleResource2Cache() {
        // 查询出所有角色
        List<Role> roles = roleMapper.selectAll();
        // 为空就直接报错
        if (CollectionUtils.isEmpty(roles)) {
            throw new BusinessException(BizErrorCode.DATA_SEARCH_NOT_FOUND, "载入缓存失败，角色为空！");
        }
        HashMap<Long, Role> idToRole = new HashMap<>();
        for (Role r : roles) {
            idToRole.put(r.getId(),r );
        }
        List<RoleResource> roleResources = roleResourceMapper.selectAll();
        if (CollectionUtils.isEmpty(roleResources)) {
            throw new BusinessException(BizErrorCode.DATA_SEARCH_NOT_FOUND, "载入缓存失败，角色资源关系为空！");
        }
        // 遍历所有角色
        HashMap<Role, List<RoleResource>> roleToRoResourceList = new HashMap<>();
        for (RoleResource roleResource : roleResources) {
            Long roleId = roleResource.getRoleId();
            Role temp = idToRole.get(roleId);
            List<RoleResource> list = roleToRoResourceList.getOrDefault(temp, new ArrayList<>());
            list.add(roleResource);
            roleToRoResourceList.put(temp, list);
        }
        for (Role r : roleToRoResourceList.keySet()) {
            List<RoleResource> l = roleToRoResourceList.get(r);
            roleCache.cacheRoleResource(r, l);
        }
        System.out.println("第一次跑成功");
        return Boolean.TRUE;

    }

    // 为多角色分配资源
    @Override
    public Boolean assignResource(@NotNull @Valid RoleResourceDTO roleResourceDTO) {
        /****安全保护*/
        // 去重相同的角色ID，利用set
        Set<Long> roleIdSet = roleResourceDTO.getRoleIds().stream().collect(Collectors.toSet());
        // set转化为list
        List<Long> roleIds = CollectionUtils.arrayToList(roleIdSet.toArray());
        // 去重相同的资源ID，利用set
        Set<Long> resourceSet = roleResourceDTO.getResourceIds().stream().collect(Collectors.toSet());
        List<Long> resourceIds = CollectionUtils.arrayToList(resourceSet.toArray());
        // 删除角色资源
        removeRolesResources(roleIds);
        // 批量导入
        boolean result = batchInsertRolesResources(roleIds, resourceIds);

        List<Role> roleList = new ArrayList<>();
        roleIds.stream().forEach(id -> {
            Role role = new Role();
            role.setId(id);
            roleList.add(role);
        });

        // 缓存新的
        roleCache.cachedMultiRolesResources(roleList);
        return result;

    }

    /**
     * 分配角色给用户
     *
     * @param userRoleDTO
     * @return
     */
    @Transactional
    @Override
    public Boolean assignUser(@NotNull @Valid UserRoleDTO userRoleDTO) {
        // 去重
        List<Long> roleIds = CollectionUtils.arrayToList((userRoleDTO.getRoleIds().stream().collect(Collectors.toSet()).toArray()));
        List<Long> userIds = CollectionUtils.arrayToList(userRoleDTO.getUserIds().stream().collect(Collectors.toSet()).toArray());

        Example example = new Example(UserRole.class);
        example.createCriteria().andIn("roleId", roleIds);
        int deletedRows = userRoleMapper.deleteByExample(example);
        if (deletedRows == 0) {
            throw new BusinessException(BizErrorCode.DATA_DELETE_NOT_FOUND, "删除数据库角色用户关联资源异常");
        }
        // 遍历每个用户分配
        int insertRows = 0;
        for (Long roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleId);

            for (Long userId : userIds) {
                userRole.setId(idGenerator.snowflakeId());
                userRole.setUserId(userId);
                userRole.setStatus(EntityConsts.INITIAL_STATUS);
                userRole.setVersion(EntityConsts.INITIAL_VERSION);
                super.baseDataStuff4Add(userRole);
//                super.baseDataStuffCommonPros(userRole);
                insertRows += userRoleMapper.insert(userRole);
            }
        }
        return insertRows > 0;
    }

    /**
     * 通过角色查询角色资源
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Node> queryResourceByRoleId(@NotNull @Valid Long roleId) {
        return roleResourceMapper.queryResourceByRoleId(roleId);
    }

    /**
     * 查询所有公司列表
     *
     * @return
     */
    @Override
    public List<Node> selectCompany() {
        return roleMapper.selectCompany();
    }

    /**
     * 增加角色用的——判断role是否存在
     *
     * @param roleDTO
     * @return
     */
    @Override
    public Boolean haveRole(@NotNull @Valid RoleDTO roleDTO) {
        Role role = BeanUtil.copy(roleDTO, Role.class);
        return roleMapper.haveRole(role) > 0;
    }

    /**
     * 编辑角色用的——判断role是否冲突
     *
     * @param roleDTO
     * @return
     */
    @Override
    public Boolean haveRole2(@NotNull @Valid RoleDTO roleDTO) {
        Role role = BeanUtil.copy(roleDTO, Role.class);
        List<Long> roleIds = roleMapper.haveRole2(role);
        if (roleIds.size() == 0) {
            return Boolean.FALSE;
        }
        if (roleIds.size() == 1 && role.getId().equals(roleIds.get(0))) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;

    }

    /**
     * 添加角色
     *
     * @param roleDTO
     * @return
     */
    @Override
    @CommonFieldStuffer(methodType = MethodTypeEnum.ADD)
    public Boolean add(@NotNull @Valid RoleDTO roleDTO) {
        // 判断角色是否已经存在
        if (haveRole(roleDTO)) {
            throw new BusinessException(BizErrorCode.DATA_INSERT_FOUND_NO_UNIQUE_RECORD, "添加失败，角色码重复！");
        }
        // 解析成role
        Role role = BeanUtil.copy(roleDTO, Role.class);
        // 雪花算法分配id
        role.setId(idGenerator.snowflakeId());
        // 造一个空角色资源插入
        List<RoleResource> roleResourceList = new ArrayList<>();
        RoleResource roleResource = new RoleResource();
        roleResource.setId(idGenerator.snowflakeId());
        //填充公共剩余字段
        super.baseDataStuff4Add(roleResource);
        roleResourceList.add(roleResource);
        // 加入缓存
        roleCache.cacheRoleResource(role, roleResourceList);
        // 加入数据库
        return roleMapper.insert(role) > 0;
    }

    /**
     * 删除角色
     *
     * @param id      角色id
     * @param version 版本号，用于实现乐观锁
     * @return
     */
    @Transactional
    @Override
    public Boolean remove(@NotNull @Valid Long id, @NotNull @Valid Long version) {
        // 模糊查询
        Example exampleRole = new Example(Role.class);
        exampleRole.createCriteria().andEqualTo("id", id);
        // 删除角色资源关系
        Example exampleRoleResource = new Example(RoleResource.class);
        exampleRoleResource.createCriteria().andEqualTo("roleId", id);
        roleResourceMapper.deleteByExample(exampleRoleResource);
        // 删除该角色与用户关系
        Example exampleUserRole = new Example(UserRole.class);
        exampleUserRole.createCriteria().andEqualTo("roleId", id);
        userRoleMapper.deleteByExample(exampleUserRole);
        // 删除角色与公司关系
        Example exampleRoleCompany = new Example(RoleCompany.class);
        exampleRoleCompany.createCriteria().andEqualTo("roleId", id);
        roleCompanyMapper.deleteByExample(exampleRoleCompany);

        boolean result = roleMapper.deleteByExample(exampleRole) > 0;
        if (result) {
            roleCache.removeCacheRoleResources(id);
        }
        return result;
    }

    /**
     * 修改
     *
     * @param roleDTO
     * @return
     */
    @Override
    @CommonFieldStuffer(methodType = MethodTypeEnum.UPDATE)
    public Boolean modify(@NotNull @Valid RoleDTO roleDTO) {
        // 当前修改结果如果重复就不修改，注意是haveRole2
        if (haveRole2(roleDTO)) {
            throw new BusinessException(BizErrorCode.DATA_INSERT_FOUND_NO_UNIQUE_RECORD, "修改失败，角色码重复！");
        }
        Role role = new Role();
        // 把dto信息给role注入
        BeanUtil.copy(roleDTO, role);
        role.setUpdatedTime(new Date());
        // 更新成功返回
        if (roleMapper.updateById(role.getId(),role.getName(),role.getCode(), role.getRemark(), role.getStatus())){
            return Boolean.TRUE;
        }
        // 更新失败返回false
        return Boolean.FALSE;

    }

    /**
     * 角色查询
     *
     * @param roleQuery
     * @return
     */
    @Pagination
    @CommonFieldStuffer(methodType = MethodTypeEnum.QUERY)
    @Override
    public CommonPage<RoleVO> commonQuery(@NotNull @Valid RoleQuery roleQuery) {
        // 分页查询
  //      Page<Role> roles = (Page<Role>) roleMapper.commonQuery(roleQuery.getName());
//        List<RoleVO> roleVOList = BeanUtil.copyList(roles, RoleVO.class, (o, o1) -> {
//            // 调用 BeanUtil.copyProperties
//            if (o == null || o1 == null) {
//                throw new BeanException("拷贝对象不可以为空", new Exception("copyList 拷贝回调错误"));
//            }
//            Role role2 = (Role) o;
//            RoleVO roleVO = (RoleVO) o1;
//            // 增加了公司信息，组织信息，租户信息
//           String companyName=companyMapper.selectName(role2.getCompanyId());
//            String orgName=organizationMapper.selectName(role2.getOrgId());
//            String tenantName=tenantMapper.selectName(role2.getTenantId());
//            roleVO.setCompanyId(role2.getCompanyId());
//            roleVO.setOrgId(role2.getOrgId());
//            roleVO.setTenantId(role2.getTenantId());
//            roleVO.setCompanyName(companyName);
//            roleVO.setOrganizationName(orgName);
//            roleVO.setTenantName(tenantName);
//            roleVO.setId(role2.getId());
//            roleVO.setStatus(role2.getStatus());
//            roleVO.setVersion(role2.getVersion());
//        });
 //       return cast2CommonPage(roles, roleVOList);
        Page<RoleVO> roles = (Page<RoleVO>) roleMapper.commonQuery2(roleQuery.getName());
        List<RoleVO> roleVOList = new ArrayList<>();
        for(RoleVO r:roles){
            RoleVO roleVO = new RoleVO();
            // 增加了公司信息，组织信息，租户信息
           String companyName=companyMapper.selectName(r.getCompanyId());
            String orgName=organizationMapper.selectName(r.getOrgId());
            String tenantName=tenantMapper.selectName(r.getTenantId());
            roleVO.setCompanyId(r.getCompanyId());
            roleVO.setOrgId(r.getOrgId());
            roleVO.setTenantId(r.getTenantId());

            roleVO.setCompanyName(companyName);
            roleVO.setOrganizationName(orgName);
            roleVO.setTenantName(tenantName);

            roleVO.setId(r.getId());
            roleVO.setCode(r.getCode());
            roleVO.setName(r.getName());
            roleVO.setRemark(r.getRemark());
            roleVO.setStatus(r.getStatus());
            roleVO.setVersion(r.getVersion());
            roleVOList.add(roleVO);
        }
        return cast2CommonPage(roles, roleVOList);
    }

    /**
     * id查询角色
     * 弃用代码为
     * //            BeanUtil.copy(role.getCompany(), roleDTO.getCompanyDTO(), CompanyDTO.class);
     * //            BeanUtil.copy(role.getOrganization(), roleDTO.getOrganizationDTO(), OrganizationDTO.class);
     * //            BeanUtil.copy(role.getTenant(), roleDTO.getTenantDTO(), TenantDTO.class);
     * @param id
     * @return
     */
    @Override
    public RoleVO queryById(@NotNull @Valid Long id) {
        RoleVO roleVO = roleMapper.selectById(id);
        return roleVO!=null ? roleVO  : new RoleVO();
    }

    /**
     * 返回角色信息
     *
     * @param id
     * @return
     */
    @Override
    public RoleVO copy(@NotNull @Valid Long id) {
        RoleVO roleVO = roleMapper.selectById(id);
        return roleVO!=null ? roleVO  : new RoleVO();
    }

    /**
     * 批量删除
     *
     * @return
     */
    @Override
//    @CommonFieldStuffer(methodType = MethodTypeEnum.DELETE)
    public Boolean batchRemove(@NotEmpty @Valid RoleDeleteDTO[] roleDeleteDTOS) {
        for (RoleDeleteDTO roleDTO : roleDeleteDTOS) {
            // 保证角色id不为空
            if (StringUtils.isEmpty(roleDTO.getId())) {
                throw new BusinessException(BizErrorCode.PARAM_VALID_FIELD_VIOLITE_RULE, "删除失败，角色id不能为空！");
            }
            // 删除角色资源关系
            Example exampleRoleResource = new Example(RoleResource.class);
            exampleRoleResource.createCriteria().andEqualTo("roleId", roleDTO.getId());
            roleResourceMapper.deleteByExample(exampleRoleResource);
            // 删除角色用户关系
            Example exampleUserRole = new Example(UserRole.class);
            exampleUserRole.createCriteria().andEqualTo("roleId", roleDTO.getId());
            userRoleMapper.deleteByExample(exampleUserRole);
            // 删除角色公司关系
            Example exampleRoleCompany = new Example(RoleCompany.class);
            exampleRoleCompany.createCriteria().andEqualTo("roleId", roleDTO.getId());
            roleCompanyMapper.deleteByExample(exampleRoleCompany);
        }
        boolean result;
        for (RoleDeleteDTO roleDTO : roleDeleteDTOS) {
            Example example = new Example(Role.class);
            example.createCriteria().
                    andEqualTo("id", roleDTO.getId()).
                    andEqualTo("version", roleDTO.getVersion());

             result = roleMapper.deleteByExample(example)>0;
            if (result) {
                roleCache.removeCacheRoleResources(roleDTO.getId());
            } else {
                throw new BusinessException(BizErrorCode.DATA_DELETE_NOT_FOUND, "批量删除角色失败，已终止");
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 模糊查询用户，包含角色信息
     *
     * @param userQuery 查询条件
     * @return
     */
    @Pagination
    @Override
    public CommonPage<UserDTO> commonQueryUser(@NotNull @Valid UserQuery userQuery) {
        Example example=new Example(User.class);
        example.setOrderByClause("updated_time DESC");
        Example.Criteria  criteria=example.createCriteria();
        if (userQuery.getCode() != null) {
            //模糊查询
            criteria.orLike("code", "%" + userQuery.getCode() + "%");
        }
        if (userQuery.getName() != null) {
            //模糊查询
            criteria.orLike("name", "%" + userQuery.getName() + "%");
        }

        Page<User> users = (Page) userMapper.selectByExample(example);

        List<UserDTO> userDTOS = BeanUtil.copyList(users, UserDTO.class);
        if (!CollectionUtils.isEmpty(userDTOS)) {
            // 增加一些dto拥有的信息
            List<Company> companies = companyMapper.selectAll();
            Map<Long, CompanyDTO> companyVOMap = new HashMap<>();
            for (Company company : companies) {
                companyVOMap.put(company.getId(), BeanUtil.copy(company, CompanyDTO.class));
            }
            List<Position> positions = positionMapper.selectAll();
            Map<Long, PositionDTO> positionHashMap = new HashMap<>();
            for (Position position : positions) {
                positionHashMap.put(position.getId(), BeanUtil.copy(position, PositionDTO.class));
            }
            List<Department> departments = departmentMapper.selectAll();
            Map<Long, DepartmentDTO> departmentDTOMap = new HashMap<>();
            for (Department department : departments) {
                departmentDTOMap.put(department.getId(), BeanUtil.copy(department, DepartmentDTO.class));
            }

            for (UserDTO userDTO : userDTOS) {
                if (!ObjectUtils.isEmpty(userDTO.getCompanyId())) {
                    userDTO.setCompany(companyVOMap.get(userDTO.getCompanyId()));
                }
                if (!ObjectUtils.isEmpty(userDTO.getPositionId())) {
                    userDTO.setPosition(positionHashMap.get(userDTO.getPositionId()));
                }
                if (!ObjectUtils.isEmpty(userDTO.getDepartmentId())) {
                    userDTO.setDepartment(departmentDTOMap.get(userDTO.getDepartmentId()));
                }
            }
        }
        // 转为为 CommonPage返回
        return cast2CommonPage(users, userDTOS);
    }


    /**
     * 查询角色资源
     *
     * @param id
     * @return
     */
    @Override
    public RoleVO queryRoleResouce(@NotNull @Valid Long id) {
        RoleVO roleVO = roleMapper.selectById(id);
        Example example = new Example(RoleResource.class);
        example.selectProperties("resourceId");
        example.createCriteria().andEqualTo("roleId", id);
        List<RoleResource> roleResources = roleResourceMapper.selectByExample(example);
        Set<Long> idSet = new HashSet<>();
        for (RoleResource roleResource : roleResources) {
            idSet.add(roleResource.getResourceId());
        }
        // 根据所有的角色id取得所有的资源
        if (!idSet.isEmpty()) {
            Example exampleResource = new Example(Resource.class);
            exampleResource.createCriteria().andIn("id", idSet);
            List<Resource> resources = resourceMapper.selectByExample(exampleResource);
            resources=resources.stream().distinct().collect(Collectors.toList());
            List<ResourceVO> resourceDTOS = BeanUtil.copyList(resources, ResourceVO.class);
            roleVO.setResourceVOS(resourceDTOS);
            return roleVO;
        } else {
            return new RoleVO();
        }
    }

    /**
     * 查询角色公司
     *
     * @param id
     * @return
     */
    @Override
    public RoleCompanyVO queryRoleCompanyById(@NotNull @Valid Long id) {
        Example example = new Example(RoleCompany.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roleId", id);
        // 获取对应角色id的 角色-授权公司 列表
        List<RoleCompany> roleCompanyList = roleCompanyMapper.selectByExample(example);
        List<Long> authCompanyIds = roleCompanyList.stream().map(RoleCompany::getAuthCompanyId)
                .collect(Collectors.toList());
        // 角色所属于的公司
        RoleCompanyVO roleCompanyVO = new RoleCompanyVO();
        roleCompanyVO.setRoleId(id);
        roleCompanyVO.setAuthCompanyIds(authCompanyIds);
        return roleCompanyVO;
    }

    /**
     * 修改角色公司关系
     *
     * @param roleCompanyDTO
     * @return
     */
    @Override
    public Boolean modifyRoleCompany(@NotNull @Valid RoleCompanyDTO roleCompanyDTO) {
        List<Long> roleIds = roleCompanyDTO.getRoleIds();
        for (Long roleId : roleIds) {
            Example selectExample = new Example(RoleCompany.class);
            Example.Criteria selectCriteria = selectExample.createCriteria();
            selectCriteria.andEqualTo("roleId", roleId);
            // 获取数据库 原有的(old) 对应角色id的 角色-授权公司 id列表
            List<RoleCompany> roleCompanyList = roleCompanyMapper.selectByExample(selectExample);
            List<Long> oldAuthCompanyIdList = roleCompanyList.stream()
                    .map(RoleCompany::getAuthCompanyId).collect(Collectors.toList());
            // 获取前端传来的 最新的(new) 角色id的 角色-授权公司 id列表
            List<Long> newAuthCompanyIdList = roleCompanyDTO.getAuthCompanyIds();

            // 旧的id列表去掉已经在新的id列表的那部分（去掉交集）是准备要删除的
            List<Long> toDelete = oldAuthCompanyIdList.stream()
                    .filter(id -> !newAuthCompanyIdList.contains(id)).collect(Collectors.toList());
            // 新的id列表去掉在旧的id列表的那部分（去掉交集）是准备要添加的
            List<Long> toInsert = newAuthCompanyIdList.stream()
                    .filter(id -> !oldAuthCompanyIdList.contains(id)).collect(Collectors.toList());

            if (!toDelete.isEmpty()) {
                Example deleteExample = new Example(RoleCompany.class);
                Example.Criteria deleteCriteria = deleteExample.createCriteria();
                deleteCriteria.andEqualTo("roleId", roleId).andIn("authCompanyId", toDelete);
                roleCompanyMapper.deleteByExample(deleteExample);
            }

            List<RoleCompany> insertRoleCompanyList = new ArrayList<>();
            toInsert.forEach(authCompanyId -> {
                RoleCompany roleCompany = new RoleCompany();
                roleCompany.setRoleId(roleId);
                roleCompany.setAuthCompanyId(authCompanyId);
                initEntity(roleCompany);
                insertRoleCompanyList.add(roleCompany);
            });
            if (!insertRoleCompanyList.isEmpty()) {
                for(RoleCompany r:insertRoleCompanyList){
                    roleCompanyMapper.insert(r);
                }
            }
        }
        return true;
    }

    /**
     * 初始化对象公共属性
     *
     * @param entity
     */
    private void initEntity(TenantBaseEntity entity) {
        entity.setId(idGenerator.snowflakeId());
        baseDataStuff4Add(entity);
        baseDataStuffCommonPros(entity);
        entity.setStatus(EntityConsts.INITIAL_STATUS);
        entity.setVersion(EntityConsts.INITIAL_VERSION);
    }

    // 删除角色
    private boolean removeRolesResources(List<Long> roleIds) {
        // 进行角色分配 采用先删除后插入的策略
        Example example=new Example(RoleResource.class);
        example.createCriteria().andIn("roleId",roleIds);
        roleIds.forEach(id -> {
            roleCache.removeCacheRoleResources(id);
        });
        return roleResourceMapper.deleteByExample(example)>0;
    }

    private boolean batchInsertRolesResources(List<Long> roleIds, List<Long> resourceIds) {
        Set<RoleResource> roleResourceSet = new HashSet<>();

        for (Long roleId : roleIds) {
            resourceIds.stream().forEach(resourceId -> {
                RoleResource roleResource = new RoleResource();
                roleResource.setRoleId(roleId);
                roleResource.setResourceId(resourceId);
                roleResource.setId(idGenerator.snowflakeId());
                roleResource.setStatus(EntityConsts.INITIAL_STATUS);
                roleResource.setVersion(EntityConsts.INITIAL_VERSION);
                // 基本数据自动添加
                baseDataStuff4Add(roleResource);

                roleResourceSet.add(roleResource);
            });
        }
        List<RoleResource> roleResourceList = CollectionUtils.arrayToList(roleResourceSet.toArray());
        // 防炸，每一百页往里插入
        int times = roleResourceList.size() / 100;
        int total = 0;
        for (int i = 0; i < times; i++) {
            total += roleResourceMapper.batchInsert(roleResourceList.subList(i * 100, (i + 1) * 100));
        }
        if (roleResourceList.size() > total) {
            total += roleResourceMapper.batchInsert(roleResourceList.subList(total, roleResourceList.size()));
        }

        return roleResourceList.size() == total;
    }
}
